import { setTags, setCacheViews, getTags, getCacheViews } from '@/utils/tag.js'
const state = {
  visitiedTags: getTags() ? getTags() : [],
  cacheViews: getCacheViews() ? getCacheViews() : []
}

const mutations = {
  ADD_VISITIED_TAGS(state, tag) {
    // const tags = state.visitiedTags
    // 是否已经包含路由路径
    const flag = state.visitiedTags.some(item => item.path === tag.path)
    !flag && (state.visitiedTags = state.visitiedTags.concat(tag))
    state.cacheViews = state.visitiedTags.map(item => item.name)
    setTags(state.visitiedTags)
    setCacheViews(state.cacheViews)
  },
  UPDATE_VISITIED_TAGS(state, tagList) {
    state.visitiedTags = tagList
    state.cacheViews = state.visitiedTags.map(item => item.name)
    setTags(state.visitiedTags)
    setCacheViews(state.cacheViews)
  },
  INSERT_VISITIED_TAGS(state, tag, i) {
    state.visitiedTags.splice(i, 0, tag)
    state.cacheViews = state.visitiedTags.map(item => item.name)
    setTags(state.visitiedTags)
    setCacheViews(state.cacheViews)
  },
  DEL_CACHE_VIEWS(state, cachViewName) {
    state.cacheViews = state.cacheViews.filter(name => name !== cachViewName)
    setTags(state.visitiedTags)
    setCacheViews(state.cacheViews)
  }
}

const actions = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
